<template>
  <div class="page-container">
    <div class="form-box">
      <template v-if="paramId">
        <page-form :model="form" ref="formRef" :rules="rules" layout="vertical" autocomplete="new-password">
          <a-tabs :active-key="tabsKey" @tab-click="onTabsChange">
            <template #extra>
              <a-button v-if="tabsKey === '1' && status === 'create'" type="primary" @click="onUpdateChange">修改</a-button>
            </template>
            <a-tab-pane key="1" title="账号信息">
              <AccountInfo ref="accountInfo" :status="status" :accountId="paramId" />
            </a-tab-pane>
            <a-tab-pane key="2" title="门店匹配">
              <StoreMatch ref="storeMatch" :accountId="paramId" />
            </a-tab-pane>
            <a-tab-pane key="3" title="车型匹配">
              <ModelMatch ref="modelMatch" :accountId="paramId" />
            </a-tab-pane>
            <a-tab-pane key="4" title="车辆匹配">
              <CarMatch ref="carMatch" :accountId="paramId" />
            </a-tab-pane>
            <a-tab-pane key="5" title="员工匹配">
              <StaffMatch ref="staffMatch" :accountId="paramId" />
            </a-tab-pane>
          </a-tabs>
        </page-form>
      </template>
      <template v-else>
        <Steps :stepList="stepList" />
        <page-form :model="form" ref="formRef" :rules="rules" layout="vertical" autocomplete="new-password">
          <div v-if="stepList[0].active">
            <AccountInfo @selectValue="onSelectValue" />
          </div>
          <div v-if="stepList[1].active">
            <StoreMatch :accountId="accountId" />
          </div>
          <div v-if="stepList[2].active">
            <ModelMatch :accountId="accountId" />
          </div>
          <div v-if="stepList[3].active">
            <CarMatch :accountId="accountId" />
          </div>
          <div v-if="stepList[4].active">
            <StaffMatch :accountId="accountId" :accountValue="accountValue" />
          </div>
        </page-form>
      </template>
    </div>
  </div>

  <page-form-footer hideCancel hideOk>
    <template v-if="(params.id && tabsKey !== '1') || status === 'edit'">
      <a-button @click="editCancelFn">关闭</a-button>
      <a-button type="primary" :loading="saveLoading" @click="onSave">保存</a-button>
    </template>

    <template v-if="!params.id">
      <template v-if="stepActive === 4">
        <a-button type="primary" :loading="saveLoading" @click="submitFn">完成</a-button>
      </template>
      <template v-else>
        <a-button v-if="stepActive === 0" @click="cancelFn">关闭</a-button>
        <a-button type="primary" @click="() => nextStepClickFn(stepActive)" :loading="saveLoading">保存并下一步</a-button>
      </template>
    </template>
  </page-form-footer>

  <!-- 等待弹窗 -->
  <WaitModal v-model="waitVisiable" />

  <!-- 队列弹窗 -->
  <TaskModal v-model="taskVisiable" @cancel="handelTaskConfig" />

  <!-- 悟空校验弹窗 -->
  <a-modal width="45vw" v-model:visible="wukongVisible" :mask-closable="false" @close="handleWukongClose">
    <template #title>账号校验</template>
    <page-form class="modal-page-form" layout="vertical" :model="form" :rules="rules" ref="modalFormRef">
      <page-form-item class="model-form-item" field="smsCode" size="1/2" label="验证码" required>
        <i-input v-model="form.smsCode" placeholder="请输入" :max-length="30" />
        <a-button type="primary" :disabled="disabled" @click="onGetCode">{{ btnText }}</a-button>
      </page-form-item>
    </page-form>
    <template #footer>
      <a-space>
        <a-button @click="handleWukongCancel">关闭</a-button>
        <a-button type="primary" :disabled="!form.smsCode" :loading="smsButtonLoading" @click="handleWuKongOk">确认</a-button>
      </a-space>
    </template>
  </a-modal>

  <!-- 飞猪短信验证码弹窗 -->
  <a-modal width="45vw" :mask-closable="false" v-model:visible="smsVisiable" @close="handelFeizhuClose">
    <template #title>短信验证</template>
    <page-form ref="smsFormRef" :model="form" :rules="rules">
      <div style="margin-bottom: 20px">{{ accountValue?.label }}平台登录需要短信验证码</div>
      <div style="margin-bottom: 20px">已发送至手机号：{{ feizhuPhone }}</div>
      <page-form-item class="model-form-item" field="smsCode" size="2/3" label="验证码" required>
        <i-input v-model="form.smsCode" placeholder="请输入" :max-length="30" />
      </page-form-item>
    </page-form>
    <template #footer>
      <a-space>
        <a-button @click="handelFeizhuCancel">关闭</a-button>
        <a-button type="primary" :disabled="!form.smsCode" :loading="smsButtonLoading" @click="handelFeizhuOk">确认</a-button>
      </a-space>
    </template>
  </a-modal>

  <!-- tab切换警告弹窗 -->
  <TabsWarningModal v-model="tabVisiable" @confirm="handleTabOk" />
</template>

<script setup lang="ts" name="ChannelForm">
  import Steps from '../components/steps.vue'
  import AccountInfo from './components/account-info.vue'
  import StoreMatch from './components/store-match.vue'
  import ModelMatch from './components/model-match.vue'
  import CarMatch from './components/car-match.vue'
  import StaffMatch from './components/staff-match.vue'

  import TabsWarningModal from './modal-box/tabs-warning-modal.vue'
  import TaskModal from './modal-box/task-modal.vue'
  import WaitModal from './modal-box/wait-modal.vue'

  import { ref, provide, onMounted, onBeforeUnmount, computed } from 'vue'
  import useNavigate from '@/hooks/useNavigate'
  import {
    verifyAccount,
    verifyLogin,
    syncAccountInfo,
    verifySmsCode,
    saveOta,
    stopVerify,
    getOtaDetail,
    syncAccountInfoStatus,
    saveChannelStoreBatch,
    saveChannelCarBatch,
    saveChannelPlateBatch,
    saveChannelStaffBatch,
  } from '@/api/business/ota'
  import { Message, Modal } from '@arco-design/web-vue'

  import getFuncOnLoopCondition from '@/utils/getFuncOnLoopCondition'
  import useCountLoop from '../hooks/useCountLoop'
  import { useRoute } from 'vue-router'
  import { loop, clear } from '../utils'

  const { navigateBack } = useNavigate()
  const { doLoop, clearLoop, btnText, disabled } = useCountLoop()

  const route = useRoute()
  const { params, query } = route
  const paramId = ref()
  console.log('index route', route)

  const status = ref('create')
  const tabsKey = ref('1')
  const tabVisiable = ref(false)
  const smsButtonLoading = ref(false)
  const saveLoading = ref(false)
  const taskVisiable = ref(false)
  const smsVisiable = ref(false)
  const wukongVisible = ref(false)
  const waitVisiable = ref(false)

  const stepActive = ref(0)
  const stepList = ref([
    { stepText: '账号信息', stepNum: 1, active: false },
    { stepText: '门店匹配', stepNum: 2, active: false },
    { stepText: '车型匹配', stepNum: 3, active: false },
    { stepText: '车辆匹配', stepNum: 4, active: false },
    { stepText: '员工匹配', stepNum: 5, active: false },
  ])

  const smsFormRef = ref()
  const modalFormRef = ref()
  const formRef = ref()
  provide('formRef', formRef)
  const form = ref<any>({})
  provide('form', form)
  const rules = ref({
    sourceId: [{ required: true, message: '请选择' }],
    username: [{ required: true, message: '请输入' }],
    password: [{ required: true, message: '请输入' }],
    subject: [{ required: true, message: '请输入' }],
    groupId: [{ required: true, message: '请输入' }],
    smsCode: [{ required: true, message: '请输入' }],
  })

  const onUpdateChange = () => {
    status.value = 'edit'
  }

  // 详情接口函数
  const feizhuPhone = ref('')
  const getDetailFn = async () => {
    const { result } = await getOtaDetail({ id: accountId.value || paramId.value })
    const { extraDataJson } = result
    const { verifyPhone } = extraDataJson
    feizhuPhone.value = verifyPhone
    return result
  }

  // 关闭，请稍后尝试
  const handelTaskConfig = () => {
    stopVerify({ id: accountId.value || paramId.value, msgId: accountTaskId.value }).then((res: any) => {
      console.log(res, 'handelTaskConfig')
      taskVisiable.value = false
      saveLoading.value = false
      clear()
    })
  }

  // 选择平台记录
  const accountValue = ref<any>({})
  const onSelectValue = (item: any) => {
    console.log(item, 'item')
    accountValue.value = item || {}
  }

  // 获取验证码
  const onGetCode = () => {
    const isLoop = doLoop()
    if (isLoop) {
      return
    }

    getVerifyCode()
  }

  /**
   * 获取验证码
   */
  const getVerifyCode = () => {
    return new Promise((resolve, reject) => {
      if (status.value === 'edit') {
        // 账号验证
        verifyLogin({ id: paramId.value })
          .then((res) => {
            console.log(res, 'edit verifyLogin then')
            accountTaskId.value = res.result // 悟空平台没有队列id，仅飞猪有
            resolve(res)
          })
          .catch((err) => {
            // Message.error(err.message)
            console.log(err, 'edit verifyLogin catch')
            reject(err)
          })
      } else {
        // 创建时账号验证
        verifyAccount({ id: accountId.value })
          .then((res) => {
            console.log(res, 'new verifyAccount then')
            accountTaskId.value = res.result
            resolve(res)
          })
          .catch((err) => {
            // Message.error(err.message)
            console.log(err, 'new verifyAccount catch')
            reject(err)
          })
      }
    })
  }

  const accountInfo = ref()
  const storeMatch = ref()
  const modelMatch = ref()
  const carMatch = ref()
  const staffMatch = ref()

  // 新增渠道保存
  // 2: 悟空平台
  // 3: 哈啰平台
  // 4: 携程平台
  // 5: 飞猪平台
  const accountId = ref() // 记录创建渠道时返回的账号id
  const accountTaskId = ref() // 队列id，飞猪和携程会返回队列id; 关闭，稍后再尝试时需要用到

  const delay = 1000
  // 轮询同步结果
  const executor = async () => {
    const response = await syncAccountInfoStatus({ id: accountId.value })
    return response
  }
  // 检查同步账号信息状态
  const condition = (response: any) => {
    console.log('checkSyncAccountCondition', response)
    return response.result === 1
  }

  // 直连渠道 铁行 飞租
  const directChannel = computed(() => {
    return form.value.sourceId && (form.value.sourceId == 7 || form.value.sourceId == 8)
  })

  // 新增保存OTA账号信息
  const saveOtaFn = async (step: number) => {
    // 铁行平台
    if (directChannel.value) {
      Modal.confirm({
        title: '提示',
        content: `${form.value.sourceId == 7 ? '铁行' : '飞租'}渠道账号保存后会跳过门店、车型、车辆、员工的匹配，请确认是否继续创建？`,
        onOk: () => {
          saveOta({ ...form.value, id: accountId.value })
            .then(() => {
              navigateBack()
            })
            .finally(() => {
              saveLoading.value = false
            })
        },
        onCancel: () => {
          saveLoading.value = false
        },
      })
    } else {
      try {
        const { result } = await saveOta({ ...form.value, id: accountId.value }) // 保存接口，获取verifyFlag状态
        const { verifyFlag, id } = result
        accountId.value = id

        if (verifyFlag === 0) {
          // 悟空平台
          if (accountValue.value.value === 2) {
            wukongVisible.value = true
          }
          // 飞猪平台
          else if (accountValue.value.value === 5) {
            taskVisiable.value = true // 打开队列弹窗

            getVerifyCode().then(() => {
              loop(
                (response: any) => {
                  if (response.closeMsg) {
                    Message.error(response.closeMsg)
                    taskVisiable.value = true
                    saveLoading.value = false
                  } else if (response.verifyFlag === 1) {
                    taskVisiable.value = false // 关闭队列弹窗
                    saveLoading.value = false
                    waitVisiable.value = true // 打开等待弹窗
                    // 轮询同步结果
                    getFuncOnLoopCondition(executor, condition, delay)
                      .then(() => {
                        waitVisiable.value = false // 关闭等待弹窗
                        saveLoading.value = false
                        stepNextFn(step)
                      })
                      .catch((error: any) => {
                        console.log(error, 'error')
                        waitVisiable.value = false // 关闭等待弹窗
                        saveLoading.value = false
                      })
                  } else if (response.extraDataJson?.errMsg) {
                    taskVisiable.value = false // 关闭队列弹窗
                    saveLoading.value = false // 关闭保存loading
                    Message.error(response.extraDataJson?.errMsg)

                    /** 新增飞猪渠道需要根据verifyType判断是否短信弹窗 */
                  } else if (response.extraDataJson?.verifyType >= 1) {
                    taskVisiable.value = false // 关闭队列弹窗
                    saveLoading.value = false
                    smsVisiable.value = true // 打开短信验证码弹窗
                  }
                },
                (error: any) => {
                  taskVisiable.value = false
                  saveLoading.value = false
                  Message.error(error.message)
                },
                getDetailFn
              )
            })
          } else {
            saveLoading.value = false
          }
        } else {
          // 其他平台
          syncAccountInfoFn(step, id)
        }
      } catch (error) {
        console.log(error, 'error')
        saveLoading.value = false
      }
    }
  }

  // 新增保存并下一步
  const nextStepClickFn = (step: any) => {
    saveLoading.value = true
    console.log('nextStepClickFn', form.value, 'step: ', step)
    formRef.value.validate((valid: any) => {
      console.log(valid, 'valid')

      if (!valid) {
        if (step === 0) {
          saveOtaFn(step)
        } else if (step === 1) {
          saveChannelStoreBatch(form.value.customList.dataList)
            .then((res: any) => {
              console.log(res, 'saveChannelStore setp: ', step)
              stepNextFn(step)
            })
            .catch((err: any) => {
              console.log(err, 'err')
            })
            .finally(() => {
              saveLoading.value = false
            })
        } else if (step === 2) {
          saveChannelCarBatch(form.value.customModalList.dataList)
            .then((res: any) => {
              console.log(res, 'saveChannelCar setp: ', step)
              stepNextFn(step)
            })
            .catch((err: any) => {
              console.log(err, 'err')
            })
            .finally(() => {
              saveLoading.value = false
            })
        } else if (step === 3) {
          saveChannelPlateBatch(form.value.customCarList.dataList)
            .then((res: any) => {
              console.log(res, 'saveChannelCar setp: ', step)
              stepNextFn(step)
            })
            .catch((err: any) => {
              console.log(err, 'err')
            })
            .finally(() => {
              saveLoading.value = false
            })
        }
        stepActive.value = step
        console.log('nextStepClickFn', stepList.value, step)
      } else {
        saveLoading.value = false
      }
    })
  }

  // 编辑保存
  const onSave = () => {
    formRef.value.validate((valid: any) => {
      console.log(valid, 'valid')

      if (!valid) {
        saveLoading.value = true
        if (tabsKey.value === '1') {
          saveOta({
            id: form.value.id,
            groupId: form.value.groupId,
            sourceId: form.value.sourceId,
            username: form.value.username,
            password: form.value.password,
            subject: form.value.subject,
            commissionRate: form.value.commissionRate,
          })
            .then((res: any) => {
              console.log(res, 'onSave')

              const { verifyFlag, sourceId, id } = res.result
              accountId.value = id // 记录创建渠道时返回的账号id

              if (verifyFlag === 0) {
                if (sourceId === 2) {
                  wukongVisible.value = true
                }

                if (sourceId === 5) {
                  taskVisiable.value = true // 打开队列弹窗

                  getVerifyCode().then(() => {
                    loop(
                      (response: any) => {
                        if (response.closeMsg) {
                          Message.error(response.closeMsg)
                          taskVisiable.value = false
                          saveLoading.value = false
                        } else if (response.verifyFlag === 1) {
                          taskVisiable.value = false
                          saveLoading.value = false
                          status.value = 'create'
                          accountInfo.value.loadData()
                        } else if (response.extraDataJson?.errMsg) {
                          taskVisiable.value = false
                          saveLoading.value = false
                          Message.error(response.extraDataJson?.errMsg)

                          /** 新增飞猪渠道需要根据verifyType判断是否短信弹窗 */
                        } else if (response.extraDataJson?.verifyType >= 1) {
                          taskVisiable.value = false
                          smsVisiable.value = true // 弹出短信验证码弹窗
                        }
                      },
                      (error: any) => {
                        taskVisiable.value = false
                        saveLoading.value = false
                        Message.error(error.message)
                      },
                      getDetailFn
                    )
                  })
                }
              } else {
                status.value = 'create'
                saveLoading.value = false
              }
            })
            .catch((err: any) => {
              console.log(err, 'err')
              // Message.error(err.data.message)
            })
            .finally(() => {
              saveLoading.value = false
            })
        }
        if (tabsKey.value === '2') {
          saveChannelStoreBatch(form.value.customList.dataList)
            .then((res: any) => {
              console.log(res, 'onSave')
              Message.success('保存成功')
              storeMatch.value.loadData()
            })
            .catch((err: any) => {
              console.log(err, 'err')
              // Message.error(err.data.message)
            })
            .finally(() => {
              saveLoading.value = false
            })
        }
        if (tabsKey.value === '3') {
          saveChannelCarBatch(modelMatch.value.shadowCustomModalList.list)
            .then((res: any) => {
              console.log(res, 'onSave')
              Message.success('保存成功')
              modelMatch.value.loadData()
              modelMatch.value.queryParam.relationCarModelId = ''
              modelMatch.value.queryParam.relationCarIdList = ''
            })
            .catch((err: any) => {
              console.log(err, 'err')
              // Message.error(err.data.message)
            })
            .finally(() => {
              saveLoading.value = false
            })
        }
        if (tabsKey.value === '4') {
          saveChannelPlateBatch(carMatch.value.shadowCustomCarList.list)
            .then((res: any) => {
              console.log(res, 'onSave')
              Message.success('保存成功')
              carMatch.value.loadData()
              carMatch.value.queryParam.channelSite = ''
              carMatch.value.queryParam.channelCarLicenseNo = ''
              carMatch.value.queryParam.relationCarId = ''
              carMatch.value.queryParam.sourceType = ''
            })
            .catch((err: any) => {
              console.log(err, 'err')
              // Message.error(err.data.message)
            })
            .finally(() => {
              saveLoading.value = false
            })
        }
        if (tabsKey.value === '5') {
          const values: string[] = []

          staffMatch.value.shadowCustomStaffList.list.forEach((item: any) => {
            if (item.channelStaffName && item.status === 'view') {
              values.push(item.channelStaffName)
            }
          })

          const isRepeat = staffMatch.value.shadowCustomStaffList.list.some((item: any, index: number) => {
            if (item.channelStaffName && item.status !== 'view') {
              if (values.includes(item.channelStaffName)) {
                formRef.value.setFields({
                  [`staffMatchList.dataList.${index}.channelStaffName`]: {
                    status: 'error',
                    message: '渠道员工重复',
                  },
                })
                saveLoading.value = false
                return true
              } else {
                values.push(item.channelStaffName)
              }
            }
          })

          if (!isRepeat) {
            saveChannelStaffBatch(staffMatch.value.shadowCustomStaffList.list)
              .then((res: any) => {
                console.log(res, 'onSave')
                Message.success('保存成功')
                staffMatch.value.loadData()
                staffMatch.value.queryParam.channelStaffName = ''
                staffMatch.value.queryParam.relationStaffId = ''
                staffMatch.value.queryParam.sourceType = ''
              })
              .catch((err: any) => {
                console.log(err, 'err')
                // Message.error(err.data.message)
              })
              .finally(() => {
                saveLoading.value = false
              })
          }
        }
      }
    })
  }

  // 完成
  const submitFn = () => {
    formRef.value.validate((valid: any) => {
      if (!valid) {
        saveLoading.value = true

        const values: string[] = []
        const isRepeat = form.value.staffMatchList.dataList.some((item: any, index: number) => {
          if (item.channelStaffName) {
            if (values.includes(item.channelStaffName)) {
              formRef.value.setFields({
                [`staffMatchList.dataList.${index}.channelStaffName`]: {
                  status: 'error',
                  message: '渠道员工重复',
                },
              })
              saveLoading.value = false
              return true
            } else {
              values.push(item.channelStaffName)
            }
          }
        })

        if (!isRepeat) {
          saveChannelStaffBatch(form.value.staffMatchList.dataList)
            .then((res: any) => {
              console.log(res, 'submitFn')
              navigateBack()
            })
            .catch((err: any) => {
              console.log(err, 'err')
            })
            .finally(() => {
              saveLoading.value = false
            })
        }
      }
    })
  }

  // 飞猪需要验证短信弹窗
  const handelFeizhuOk = () => {
    smsFormRef.value.validate(async (valid: any) => {
      if (!valid) {
        smsButtonLoading.value = true

        if (status.value === 'edit') {
          // 同步账号信息
          try {
            const data = await verifySmsCode({ id: accountId.value, smsCode: form.value.smsCode })
            console.log(data, '飞猪创建时同步账号信息接口')

            loop(
              (response: any) => {
                if (response.closeMsg) {
                  Message.error(response.closeMsg)
                  smsButtonLoading.value = false
                } else if (response.verifyFlag === 1) {
                  smsVisiable.value = false
                  smsButtonLoading.value = false
                  status.value = 'create'
                  accountInfo.value.loadData()
                } else if (response.extraDataJson?.errMsg) {
                  smsButtonLoading.value = false
                  Message.error(response.extraDataJson?.errMsg)

                  /** 飞猪平台已经弹出短信弹窗则不需要再判断verifyType */
                } else if (response?.loop) {
                  response.loop()
                }
              },
              (error: any) => {
                smsButtonLoading.value = false
                Message.error(error.message)
              },
              getDetailFn
            )
          } catch (error) {
            smsButtonLoading.value = false
          }
        } else {
          // 创建时同步账号信息
          const data = await syncAccountInfo({ id: accountId.value, smsCode: form.value.smsCode })
          console.log(data, '飞猪创建时同步账号信息接口')

          loop(
            (response: any) => {
              if (response.closeMsg) {
                smsButtonLoading.value = false
                Message.error(response.closeMsg)
              } else if (response.verifyFlag === 1) {
                smsVisiable.value = false // 关闭短信验证码弹窗
                smsButtonLoading.value = false // 关闭短信验证码确定按钮loading
                waitVisiable.value = true // 打开等待弹窗

                // 轮询同步结果
                getFuncOnLoopCondition(executor, condition, delay)
                  .then(() => {
                    waitVisiable.value = false
                    saveLoading.value = false
                    stepNextFn(stepActive.value)
                  })
                  .catch((error: any) => {
                    console.log(error, '飞猪轮询同步结果 error')
                    waitVisiable.value = false
                    saveLoading.value = false
                  })
              } else if (response.extraDataJson?.errMsg) {
                smsButtonLoading.value = false
                Message.error(response.extraDataJson?.errMsg)

                /** 飞猪平台已经弹出短信弹窗则不需要再判断verifyType */
              } else if (response?.loop) {
                response.loop()
              }
            },
            (error: any) => {
              smsButtonLoading.value = false
              Message.error(error.message)
            },
            getDetailFn
          )
        }
      }
    })
  }

  const handelFeizhuCancel = () => {
    smsVisiable.value = false
    smsFormRef.value.resetFields()
    saveLoading.value = false
    smsButtonLoading.value = false
    stopVerify({ id: accountId.value || paramId.value }).then((res: any) => {
      console.log(res, 'handelFeizhuCancel')
      taskVisiable.value = false
      saveLoading.value = false
      clear()
    })
  }

  const handelFeizhuClose = () => {
    smsVisiable.value = false
    smsFormRef.value.resetFields()
    saveLoading.value = false
    smsButtonLoading.value = false
    clear()
  }

  const handleWuKongOk = () => {
    modalFormRef.value.validate(async (valid: any) => {
      if (!valid) {
        smsButtonLoading.value = true

        if (status.value === 'edit') {
          try {
            const data = await verifySmsCode({ id: accountId.value, smsCode: form.value.smsCode })
            console.log('悟空创建时同步账号信息接口', data)

            loop(
              (response: any) => {
                if (response.closeMsg) {
                  Message.error(response.closeMsg)
                  smsButtonLoading.value = false
                } else if (response.verifyFlag === 1) {
                  wukongVisible.value = false
                  smsButtonLoading.value = false
                  status.value = 'create'
                  accountInfo.value.loadData()
                } else if (response.extraDataJson?.errMsg) {
                  smsButtonLoading.value = false
                  Message.error(response.extraDataJson?.errMsg)

                  /** 飞猪平台已经弹出短信弹窗则不需要再判断verifyType */
                } else if (response?.loop) {
                  response.loop()
                }
              },
              (error: any) => {
                smsButtonLoading.value = false
                Message.error(error.message)
              },
              getDetailFn
            )
          } catch (error) {
            smsButtonLoading.value = false
          }
        } else {
          // 创建时同步账号信息
          const data = await syncAccountInfo({ id: accountId.value, smsCode: form.value.smsCode })
          console.log('创建时同步账号信息', data)

          loop(
            (response: any) => {
              console.log(response, 'response')

              if (response.closeMsg) {
                smsButtonLoading.value = false
                Message.error(response.closeMsg)
              } else if (response.verifyFlag === 1) {
                wukongVisible.value = false // 关闭短信验证码弹窗
                smsButtonLoading.value = false // 关闭短信验证码确定按钮loading
                waitVisiable.value = true // 打开等待弹窗

                // 轮询同步结果
                getFuncOnLoopCondition(executor, condition, delay)
                  .then(() => {
                    waitVisiable.value = false
                    saveLoading.value = false
                    stepNextFn(stepActive.value)
                  })
                  .catch((error: any) => {
                    console.log(error, '悟空轮询同步结果 error')
                    waitVisiable.value = false
                    saveLoading.value = false
                  })
              } else if (response.extraDataJson?.errMsg) {
                smsButtonLoading.value = false
                Message.error(response.extraDataJson?.errMsg)
              } else if (response?.loop) {
                response.loop()
              }
            },
            (error: any) => {
              smsButtonLoading.value = false
              Message.error(error.message)
            },
            getDetailFn
          )
        }
      }
    })
  }

  const handleWukongCancel = () => {
    wukongVisible.value = false
    modalFormRef.value.resetFields()
    saveLoading.value = false
    disabled.value = false
    btnText.value = '获取验证码'
    clearLoop()
    stopVerify({ id: accountId.value || paramId.value }).then((res: any) => {
      console.log(res, 'handleWukongCancel')
      taskVisiable.value = false
      saveLoading.value = false
      clear()
    })
  }

  const handleWukongClose = () => {
    wukongVisible.value = false
    modalFormRef.value.resetFields()
    saveLoading.value = false
    disabled.value = false
    btnText.value = '获取验证码'
    clearLoop()
    clear()
  }

  // 携程与哈啰平台同步账号信息
  const syncAccountInfoFn = async (step: number, id: number) => {
    try {
      // 创建时同步账号信息
      const { result } = await syncAccountInfo({ id })
      console.log(result, '哈啰创建时同步账号信息接口')
      taskVisiable.value = true

      getFuncOnLoopCondition(executor, condition, delay)
        .then(() => {
          taskVisiable.value = false
          saveLoading.value = false
          stepNextFn(step)
        })
        .catch((error: any) => {
          // Message.error(error.message)
          console.log(error, 'error')
          taskVisiable.value = false
          saveLoading.value = false
        })
    } catch (error) {
      console.log(error, 'error')
      saveLoading.value = false
    }
  }

  const editCancelFn = () => {
    if (status.value === 'edit') {
      status.value = 'create'
      accountInfo.value.loadData()
    } else {
      formRef.value.resetFields()
      navigateBack()
    }
  }

  // 返回事件
  const cancelFn = () => {
    navigateBack()
  }

  const tabValue = ref()
  const onTabsChange = (val: string | number) => {
    tabValue.value = val

    if (tabsKey.value === '1') {
      if (status.value === 'edit') {
        tabVisiable.value = true
        return
      }
    }

    if (tabsKey.value === '2') {
      const isTrue = form.value.customList.dataList.every((item: any) => {
        return item.status === 'create'
      })
      if (!isTrue) {
        tabVisiable.value = true
        return
      }
    }

    if (tabsKey.value === '3') {
      const isTrue = form.value.customModalList.dataList.every((item: any) => {
        return item.status === 'create'
      })
      if (!isTrue) {
        tabVisiable.value = true
        return
      }
    }

    if (tabsKey.value === '4') {
      const isTrue = form.value.customCarList.dataList.every((item: any) => {
        return item.status === 'create'
      })
      if (!isTrue) {
        tabVisiable.value = true
        return
      }
    }

    if (tabsKey.value === '5') {
      const isTrue = form.value.staffMatchList.dataList.every((item: any) => {
        return item.status === 'view'
      })
      if (!isTrue) {
        tabVisiable.value = true
        return
      }
    }

    tabsKey.value = val as string
  }

  const handleTabOk = () => {
    console.log(tabsKey.value, 'tabValue.value 2')
    if (tabsKey.value === '1') {
      status.value = 'create'
    }
    if (tabsKey.value === '2') {
      form.value.customList.dataList = JSON.parse(storeMatch.value.copyCustomList)
    }
    if (tabsKey.value === '3') {
      form.value.customModalList.dataList = JSON.parse(modelMatch.value.copyCustomModalList)
    }
    if (tabsKey.value === '4') {
      form.value.customCarList.dataList = JSON.parse(carMatch.value.copyCustomCarList)
    }
    if (tabsKey.value === '5') {
      form.value.staffMatchList.dataList = JSON.parse(staffMatch.value.copyCustomStaffList)
    }
    tabVisiable.value = false
    tabsKey.value = tabValue.value
  }

  const stepNextFn = (step: number) => {
    stepList.value[step].active = false
    stepList.value[++step].active = true
    stepActive.value = step
  }

  // const stepPrevFn = (step: number) => {
  //   stepList.value[step].active = false
  //   stepList.value[--step].active = true
  //   stepActive.value = step
  // }

  onMounted(() => {
    if (params.id || query.tabKey) {
      paramId.value = params.id
      stepList.value[0].active = false
      tabsKey.value = (query.tabKey as string) || '1'
    } else {
      stepList.value[0].active = true
    }
  })

  onBeforeUnmount(() => {
    console.log('onBeforeUnmount', form.value)
    status.value = 'create'
    btnText.value = '获取验证码'
    disabled.value = false
    saveLoading.value = false
    smsButtonLoading.value = false
    taskVisiable.value = false
    smsVisiable.value = false
    wukongVisible.value = false
    waitVisiable.value = false
    tabVisiable.value = false
    formRef.value.resetFields()
    smsFormRef.value.resetFields()
    modalFormRef.value.resetFields()
    clear()
    clearLoop()
  })
</script>

<style lang="less" scoped>
  .modal-page-form {
    // overflow: hidden;
    // margin: 0;
    // height: 300px;
    :deep(.arco-row) {
      margin-left: 0 !important;
      margin-right: 0 !important;
    }
    :deep(.arco-col) {
      padding: 0 10px !important;
    }
  }
</style>
